package com.laicunba.event.listener;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.UserCreateEvent;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.RegistryService;
import com.laicunba.service.accounting.NewUserRewardService;
import com.laicunba.service.mq.ActiveMQMessageFactory;
import com.laicunba.service.mq.ActiveMQService;
import com.laicunba.util.StringUtil;

@Component
public class UserCreateListener implements ApplicationListener<UserCreateEvent> {
	private static final Logger LOG = Logger.getLogger(UserCreateListener.class);
	@Autowired
	private RegistryService registryService;

	@Autowired
	private NewUserRewardService newUserRewardService;
	@Autowired
	private ActiveMQService activeMQService;

	@Override
	public void onApplicationEvent(UserCreateEvent event) {
		if (event.getSource() == null) {
			return;
		}

		// 发消息
		JSONObject msg = ActiveMQMessageFactory.createUsrCreateMessage((UserDO) event.getSource());
		activeMQService.sendTopics("lcb.core.usr.create", msg.toJSONString());

		Map<String, String> map = registryService.likeKey("act.regist.");
		if (!"true".equalsIgnoreCase(map.get("act.regist.open"))) {
			return;
		}
		String amount = map.get("act.regist.amount");
		String name = map.get("act.regist.name");
		String summary = map.get("act.regist.summary");
		if (!StringUtil.isNumber(amount) || StringUtil.isEmpty(name, summary)) {
			LOG.warn("注册活动已开启,但配置信息不全(或有错),放弃活动内容!");
			return;
		}
		try {
			UserDO user = (UserDO) event.getSource();
			if(user==null){
				return;
			}
			if(StringUtil.isNotEmpty(user.getChannel())&&user.getChannel().startsWith("no-award")){
				return;
			}
			newUserRewardService.doAutoBuy(user.getId(), BigDecimal.valueOf(Double.valueOf(amount)));
		} catch (Exception e) {
			LOG.error("注册活动失败", e);
		}
	}

}
